import { lazy, Suspense } from "react";
import type { RouteObject } from "react-router-dom";

// 加载中组件
const Loading = () => <div>加载中...</div>;

// 修改接口定义以匹配实际的菜单数据结构
interface MenuApiData {
  id: number;
  parentId: number;
  menuName: string; // 使用 menuName 而不是 title
  url: string; // 使用 url 而不是 path
  description?: string;
  editAble: number;
  menuList?: MenuApiData[]; // 使用 menuList 而不是 children
  component?: string;
}

// 修改组件映射表
const componentMap: Record<
  string,
  () => Promise<{ default: React.ComponentType<unknown> }>
> = {
  home: () => import("../pages/home/index.tsx"),
  userManager: () => import("../pages/userManager/index.tsx"),
  menuManager: () => import("../pages/menuManager/index.tsx"),
  operationLog: () => import("../pages/operationLog/index.tsx"),
  roleManager: () => import("../pages/roleManager/index.tsx"),
  common: () => import("../pages/common/index.tsx"),
  error: () => import("../pages/error/index.tsx"),
};

const loadComponent = (component: string) => {
  // 如果 component 包含 'common'，统一加载 common 组件
  const loader = component.includes("common")
    ? componentMap["common"]
    : componentMap[component] || componentMap["error"];

  if (!loader) {
    console.error(`Component not found: ${component}`);
    return <div>组件加载失败</div>;
  }

  const Component = lazy(() => loader());

  return (
    <Suspense fallback={<Loading />}>
      <Component key={component} />
    </Suspense>
  );
};

// 修改菜单转换函数，使用正确的字段名
export const menuToRoutes = (menuList: MenuApiData[]): RouteObject[] => {
  return menuList.map((menu) => {
    const route: RouteObject = {
      path: menu.url, // 使用 url 字段
      handle: { title: menu.menuName }, // 使用 menuName 字段
      element: menu.component ? loadComponent(menu.component) : undefined,
    };

    // 使用 menuList 字段处理子菜单
    if (menu.menuList && menu.menuList.length > 0) {
      route.children = menuToRoutes(menu.menuList);
    }

    return route;
  });
};

// 修改菜单项转换函数
export const menuToMenuItems = (menuList: MenuApiData[]): any[] => {
  return menuList.map((menu) => {
    const menuItem = {
      key: menu.url, // 使用 url 字段作为 key
      title: menu.menuName, // 使用 menuName 字段作为标题
      path: menu.url, // 使用 url 字段作为路径
    };

    // 使用 menuList 字段处理子菜单
    if (menu.menuList && menu.menuList.length > 0) {
      menuItem.children = menuToMenuItems(menu.menuList);
    }

    return menuItem;
  });
};
